// eslint-disable-next-line no-unused-vars
import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserInfo, amendPsaaWord } from '@/api/user'
import { Message } from 'element-ui'
import { constantRoutes } from '@/router'
import { resetRouter } from '@/router'

const state = {
  token: getToken(),
  userInfo: {}, // 这里有一个空对象，为了放置后面取数据报错
  Routers: constantRoutes // 路由存储
}

const getters = {

}

const mutations = {
  isToken(state, token) {
    state.token = token // 存储Token到state
    setToken(token) // 存储Token到cookie
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  loginOut(state) {
    state.token = ''
    state.userInfo = {}
    removeToken()
  },
  storeRouter(state, getRouter) { // 路由存储到state
    state.Routers = [...constantRoutes, ...getRouter]
  }
}

const actions = {
  async loginAxios(context, ruleForm) {
    const res = await login(ruleForm) // 发起登录请求
    context.commit('isToken', res.data.data) // 调用mutations里面的方法，存储token到state
  },
  async getUserInfo(context) { // 获取用户信息
    const result = await getUserInfo()
    context.commit('setUserInfo', result.data.data)
    return result
  },
  setloginOut(contest) { // 退出登录请求
    contest.commit('loginOut')
    resetRouter() // 重置路由
  },
  // 密码修改
  async alterPassword(context, data) {
    const res = await amendPsaaWord(data)
    Message({
      message: res.data.message,
      type: 'success'
    })
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
